import {
  api
} from '@/api'
import router from '@/router'
import Layout from '@/components/layout'
const _import = require('../../router/_import_' + process.env.NODE_ENV)
const state = {
  promptData: '',
  isFirst: true,
  isAuth: false,
  isW7: false,
  isShowPrompt: false, // 是否显示到期提醒
  systemCopyInfo: '', // 获取微擎系统版本信息
  allRoutes: [], // 所有页面
  routes: [],
  have_police_notice: false, // 是否有求救通知权限
  have_police_read: false, // 求救通知是否有阅读权限
  have_order_notice: false, // 是否订单通知权限
  have_order_read: false, // 订单通知是否有阅读权限
  notice_num: 0,
  police_num: 0,
  notice_info: {},
  notice_audio: {},
  help_voice: '',
  ShopOrder: false,
  ShopBellOrder: false,
  ShopRefund: false,
  ShopBellRefund: false,
  ShopRefuseOrder: false,
  ShopOrderPage: false,
  ShopBellOrderPage: false,
  ShopRefundPage: false,
  ShopBellRefundPage: false,
  ShopRefuseOrderPage: false,
  userInfo: {},
  auth: {},
  old_attendant_name: '技师',
  attendant_name: '技师',
  agent_service_type: 0
}
const getters = {
  isAuth: state => {
    return state.isAuth
  },
  isW7: state => {
    return state.isW7
  },
  routes: state => {
    return state.routes
  }
}
const mutations = {
  // 修改到期提醒数据
  changePromptData (state, item) {
    let { status } = item
    if (status === 2) {
      state.isShowPrompt = true
    } else if (status === 1 && state.isFirst) {
      state.isFirst = false
      state.isShowPrompt = true
    }
    state.promptData = item
  },
  // 修改是否显示到期提醒
  changeIsShowPrompt (state, item) {
    state.isShowPrompt = item
  },
  changeRoutesItem (state, item) {
    // console.log('changeItem ==>', item)
    let { key, val } = item
    state[key] = val
  },
  saveRoutes (state, item = []) {
    state.routes = item
    state.isAuth = true
  }
}
const actions = {
  changeMutaRoutesItem ({ commit }, obj) {
    commit('changeRoutesItem', obj)
  },
  async getUserPromission ({
    commit
  }, obj) {
    // 正式请求接口获取路由
    let [w7Tmp, saasAuth, adminNode] = await Promise.all([api.base.getW7TmpV2(), api.base.getSaasAuth(), api.account.adminNodeInfo()])
    let { w7tmp } = w7Tmp.data
    let auth = saasAuth.data
    let { is_admin: isAdmin, node, attendant_name: attendant = '技师' } = adminNode.data

    commit('changeRoutesItem', { key: 'attendant_name', val: attendant })

    // isAdmin = 2
    // node = [{ node: 'ShopOrder', auth: ['pagedata'] }, { node: 'ShopOrderNotice', auth: ['view'] }]
    // node = [{ node: 'SystemAdapay', auth: [] }]

    for (let i in auth) {
      auth[i] = auth[i] === true ? 1 : auth[i] === false ? 0 : auth[i]
    }

    // examine 微信代码提交审核
    // employ 应用设置
    // link 链接管理
    auth.examine = auth.wechat === 1 ? 1 : 0
    auth.employ = (auth.h5 === 1 || auth.app === 1) ? 1 : 0
    auth.link = auth.h5 === 1 ? 1 : 0

    commit('changeRoutesItem', { key: 'systemCopyInfo', val: w7tmp })
    commit('changeRoutesItem', { key: 'auth', val: auth })

    let routes = JSON.parse(JSON.stringify(obj.routes))
    commit('changeRoutesItem', { key: 'allRoutes', val: routes })
    let allRoutes = []
    let sysAuthArr = ['examine', 'wechat', 'h5', 'app', 'employ', 'link', 'virtual', 'reminder', 'fdd']
    let routesAuthArr = ['/dynamic', '/store', '/account', '/agent', '/adapay']
    routes.map(item => {
      if (routesAuthArr.includes(item.path)) {
        let newAuth = item.path === '/account' ? auth.node || auth.mobilenode : item.path === '/agent' ? isAdmin !== 0 ? true : auth.fdd : auth[item.path.split('/')[1]]
        item.auth = newAuth
        item.hidden = !newAuth
      }
      if (item.path === '/custom') {
        let memberInd = item.meta.subNavName.findIndex(aitem => {
          return aitem.name === 'CustomMemberManage'
        })
        if (memberInd !== -1 && !auth.member) {
          item.meta.subNavName.splice(memberInd, 1)
        }
        item.children = item.children.filter(aitem => {
          if (aitem.path === 'user') {
            let { auth: userAuth } = aitem.meta.pagePermission[0]
            let newUserAuth = userAuth.filter(bitem => {
              return (bitem.includes('memberGrowth') && auth.member) || !bitem.includes('memberGrowth')
            })
            aitem.meta.pagePermission[0].auth = newUserAuth
          }
          aitem.hidden = ['member/level/edit', 'member/rights/edit'].includes(aitem.path) ? true : aitem.path.includes('member/') && !auth.member
          return (aitem.path.includes('member/') && auth.member) || !aitem.path.includes('member/')
        })
      }
      if (item.path === '/finance') {
        item.children.map(aitem => {
          if (aitem.path === 'record') {
            let { auth: userAuth } = aitem.meta.pagePermission[0]
            let newUserAuth = userAuth.filter(bitem => {
              return (bitem.includes('adapayCashOut') && auth.adapay) || !bitem.includes('adapayCashOut')
            })
            aitem.meta.pagePermission[0].auth = newUserAuth
          }
        })
      }
      if (item.path === '/sys') {
        item.meta.subNavName.map(aitem => {
          aitem.url.map(bitem => {
            let authUrl = bitem.url.split('/sys/')[1]
            let authKey = authUrl.split('-')[0]
            if (sysAuthArr.includes(authKey)) {
              bitem.auth = auth[authKey]
              let ind = item.children.findIndex(citem => {
                return citem.path.includes(authKey)
              })
              item.children[ind].meta.auth = auth[authKey]
              if (authUrl === 'virtual-set') {
                item.children[ind + 1].meta.auth = auth[authKey]
              }
              if (authUrl === 'fdd-set') {
                item.children[ind + 1].meta.auth = auth[authKey]
              }
            }
          })
        })
        let subNavName = JSON.parse(JSON.stringify(item.meta.subNavName))
        subNavName.map(aitem => {
          aitem.url = aitem.url.filter(bitem => {
            return bitem.auth === 1
          })
        })
        item.meta.subNavName = subNavName
        item.children = item.children.filter(aitem => {
          return aitem.meta.auth === 1
        })
      }
    })

    let routesAuthArrDatas = routes.filter(item => {
      return (routesAuthArr.includes(item.path) && item.auth) || !routesAuthArr.includes(item.path)
    })
    routes = routesAuthArrDatas

    // 普通用户
    if (auth.node && isAdmin === 2) {
      let arr = node.map(item => { return item.node })
      let isHaveArticle = arr.includes('MarketArticle') && arr.includes('MarketArticleEnroll') ? 1 : arr.includes('MarketArticle') || arr.includes('MarketArticleEnroll') ? arr.includes('MarketArticle') ? 2 : 3 : 0
      let isHavePayment = arr.includes('SystemPaymentWechat') && arr.includes('SystemPaymentAlipay') ? 1 : arr.includes('SystemPaymentWechat') || arr.includes('SystemPaymentAlipay') ? arr.includes('SystemPaymentWechat') ? 2 : 3 : 0
      let isHaveVirtual = arr.includes('SystemVirtualSet') && arr.includes('SystemVirtualRecord') ? 1 : arr.includes('SystemVirtualSet') || arr.includes('SystemVirtualRecord') ? arr.includes('SystemVirtualSet') ? 2 : 3 : 0
      let isHaveFdd = arr.includes('SystemFddSet') && arr.includes('SystemFddRecord') ? 1 : arr.includes('SystemFddSet') || arr.includes('SystemFddRecord') ? arr.includes('SystemFddSet') ? 2 : 3 : 0
      let isHaveCarFee = arr.includes('SystemCarFeeSet') && arr.includes('SystemCarFeeCity') ? 1 : arr.includes('SystemCarFeeSet') || arr.includes('SystemCarFeeCity') ? arr.includes('SystemCarFeeSet') ? 2 : 3 : 0
      // console.log(isHaveArticle, isHavePayment, isHaveVirtual, isHaveFdd, isHaveCarFee)
      let newRoutes = []
      routes.map(item => {
        if (item.hidden) return
        let children = []
        item.children.map(aitem => {
          if (arr.includes(aitem.name)) {
            let ind = node.findIndex(bitem => {
              return bitem.node === aitem.name
            })
            aitem.meta.pagePermission.map(citem => {
              if (citem.title === aitem.name) {
                citem.auth = node[ind].auth
              }
            })

            if ((isHaveArticle === 2 && aitem.name === 'MarketArticle') || (isHavePayment === 2 && aitem.name === 'SystemPaymentWechat') || (isHaveVirtual === 2 && aitem.name === 'SystemVirtualSet') || (isHaveFdd === 2 && aitem.name === 'SystemFddSet') || (isHaveCarFee === 2 && aitem.name === 'SystemCarFeeSet')) {
              aitem.meta.pagePermission.splice(1, 1)
            }
            if ((isHaveArticle === 3 && aitem.name === 'MarketArticleEnroll') || (isHavePayment === 3 && aitem.name === 'SystemPaymentAlipay') || (isHaveVirtual === 3 && aitem.name === 'SystemVirtualRecord') || (isHaveFdd === 3 && aitem.name === 'SystemFddRecord') || (isHaveCarFee === 3 && aitem.name === 'SystemCarFeeCity')) {
              aitem.meta.pagePermission.splice(0, 1)
            }

            children.push(aitem)
          }
        })
        let hidden = item.children.filter(item => {
          return item.hidden
        })
        if (children.length > 0) {
          let arr = children.map(item => {
            return item.name
          })
          item.children = [...children, ...hidden]
          if (item.meta.subNavName && item.meta.subNavName.length > 0) {
            let subNavName = []
            item.meta.subNavName.map(aitem => {
              if (aitem.name === 'MarketManage') {
                if (isHaveArticle === 3) {
                  let urlInd = aitem.url.findIndex(citem => {
                    return citem.name === 'MarketArticle'
                  })
                  aitem.url[urlInd].url = '/market/article/enroll'
                }
              }
              if (aitem.name === 'SystemSetting') {
                if (isHavePayment === 3) {
                  let urlInd = aitem.url.findIndex(citem => {
                    return citem.name === 'SystemPayment'
                  })
                  aitem.url[urlInd].url = '/sys/alipay'
                }
              }
              if (aitem.name === 'SystemMessageSet') {
                if (isHaveVirtual === 3) {
                  let urlInd = aitem.url.findIndex(citem => {
                    return citem.name === 'SystemVirtual'
                  })
                  aitem.url[urlInd].url = '/sys/virtual-record'
                }
              }
              if (aitem.name === 'SystemOther') {
                if (isHaveFdd === 3) {
                  let urlInd = aitem.url.findIndex(citem => {
                    return citem.name === 'SystemFdd'
                  })
                  aitem.url[urlInd].url = '/sys/fdd-record'
                }
                if (isHaveCarFee === 3) {
                  let urlInd = aitem.url.findIndex(citem => {
                    return citem.name === 'SystemCarFee'
                  })
                  aitem.url[urlInd].url = '/sys/car-fee-city'
                }
              }

              let url = aitem.url.filter(bitem => {
                return arr.includes(bitem.name) || (isHaveArticle && bitem.name === 'MarketArticle') || (isHavePayment && bitem.name === 'SystemPayment') || (isHaveVirtual && bitem.name === 'SystemVirtual') || (isHaveCarFee && bitem.name === 'SystemCarFee')
              })

              if (url.length > 0) {
                subNavName.push({ name: aitem.name, url })
              }
            })
            if (subNavName.length > 0) {
              item.redirect = subNavName[0].url[0].url
              item.meta.subNavName = subNavName
            }
          }
          newRoutes.push(item)
        }
      })
      allRoutes = [...newRoutes, {
        path: '*',
        redirect: '/404',
        hidden: true
      }]
    } else {
      allRoutes = routes
    }

    let police = -1
    let policeAuth = []
    let order = -1
    let orderAuth = []
    allRoutes.findIndex((item, index) => {
      if (item.path === '/shop') {
        item.children.map(aitem => {
          if (['ShopOrder', 'ShopBellOrder', 'ShopRefund', 'ShopBellRefund', 'ShopRefuseOrder'].includes(aitem.name)) {
            commit('changeRoutesItem', { key: `${aitem.name}Page`, val: true })
            commit('changeRoutesItem', { key: aitem.name, val: aitem.name === 'ShopRefuseOrder' ? true : aitem.meta.pagePermission[0].auth.includes('view') })
          }
        })
      }
      if (item.path === '/notice') {
        police = item.children.findIndex(item => {
          return item.name === 'NoticeList'
        })
        policeAuth = police === -1 ? [] : item.children[police].meta.pagePermission[0].auth
      }
      if (item.path === '/order') {
        order = index
        orderAuth = item.children[0].meta.pagePermission[0].auth
      }
      if (item.path === '/account') {
        if (isAdmin === 0 && auth.mobilenode !== 1) {
          allRoutes.splice(index, 1)
        } else {
          if (auth.mobilenode !== 1) {
            item.meta.subNavName.splice(0, 1)
            item.redirect = '/account/role'
          }
          if (isAdmin === 1 && auth.node !== 1) {
            item.meta.subNavName.splice(1, 1)
          }
          if (auth.mobilenode !== 1 || (isAdmin === 1 && auth.node !== 1)) {
            let nodeAuthArr = auth.mobilenode !== 1 ? ['phone'] : ['role', 'list']
            let arr = item.children.filter(aitem => {
              return !nodeAuthArr.includes(aitem.path)
            })
            item.children = arr
          }
        }
      }
    })
    commit('changeRoutesItem', { key: 'have_police_notice', val: police !== -1 })
    commit('changeRoutesItem', { key: 'have_police_read', val: policeAuth.includes('read') })
    commit('changeRoutesItem', { key: 'have_order_notice', val: order !== -1 })
    commit('changeRoutesItem', { key: 'have_order_read', val: orderAuth.includes('read') })

    commit('saveRoutes', allRoutes)
    obj.routes = allRoutes
    let { path = '' } = obj.to
    let arr = []
    allRoutes.map(item => {
      if (item.children && item.children.length) {
        item.children.map(aitem => {
          arr.push(`${item.path}/${aitem.path}`)
        })
      }
    })
    if (!path || (path && !arr.includes(path))) {
      obj.to = allRoutes[0]
    }
    routerGo(allRoutes, obj)
  }
}

export default {
  state,
  getters,
  mutations,
  actions
}

function routerGo (routes, obj) {
  let getRouter = filterAsyncRouter(routes) // 过滤路由
  router.options.routes.push(...getRouter)
  router.addRoutes(getRouter) // 动态添加路由
  // localStorage.setItem('routes', JSON.stringify(getRouter))
  obj.next({
    ...obj.to,
    replace: true
  })
}

function filterAsyncRouter (asyncRouterMap) { // 遍历后台传来的路由字符串，转换为组件对象
  const accessedRouters = asyncRouterMap.filter(route => {
    if (route.component) {
      if (route.component === 'Layout') { // Layout组件特殊处理
        route.component = Layout
      } else {
        route.component = _import(route.component)
      }
    }
    if (route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children)
    }
    return true
  })
  return accessedRouters
}
